﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LuckyLoot.Presentation.BasePage;
using LuckyLoot.ServiceFacade.Contracts;
using LuckyLoot.ServiceFacade.Implementation;
using LuckyLoot.Domain.Entities.People;
using LuckyLoot.Common.Validation;

namespace LuckyLoot.Presentation
{
    public partial class UserPage : LuckyLootPage
    {
        private const string QueryStringUserID = "UserID";

        private IUserService _userService;
        public IUserService UserService
        {
            get
            {
                if (_userService == null)
                    _userService = new UserService();

                return _userService;
            }
        }

        public int UserID
        {
            set
            {
                this.ViewState[QueryStringUserID] = value;
            }
            get
            {
                int viewStateTypedUserID;

                if (this.ViewState[QueryStringUserID] != null)
                {
                    if (Int32.TryParse(this.ViewState[QueryStringUserID].ToString(), out viewStateTypedUserID))
                        return viewStateTypedUserID;
                }

                return 0;
            }
        }

        public bool HasSelectedRecord
        {
            get
            {
                return UserID > 0;
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    //string name, string phone, string email, string password, string facebook, bool isAdmin, bool isTattooArtist
                    var userIDString = HttpContext.Current.Request.QueryString[QueryStringUserID];
                    this.SelectRecord(userIDString);
                }
                
                this.SaveUser.Click += new EventHandler(SaveUserClick);

                this.BindGrid();
            }
            catch (Exception ex)
            {
                MasterPage.ShowErrorMessage(ex.Message);
            }
        }

        private void SetCommandsVisibility()
        {
            
        }

        private void SelectRecord(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                int intID;
                if (Int32.TryParse(id, out intID))
                    SelectRecord(intID);
            }

        }

        private void SelectRecord(int id)
        {
            ValidState.Requires<ArgumentException>(id > 0);
            var user = this.UserService.GetUser(id);

            SelectRecord(user);
        }

        private void SelectRecord(LuckyLoot.Domain.Entities.People.User user)
        {
            this.userName.Text = user.Name;
            this.userPhone.Text = user.Phone;
            this.userEmail.Text = user.Email;
            this.userPassword.Text = user.Password; 
            this.userFacebook.Text = user.Facebook;
            this.userAdmin.Checked = user.IsAdmin;
            this.userTattooArtist.Checked = user is TattooArtist;

            this.UserID = user.Id;
        }

        private void ClearRecordSelection()
        {
            this.UserID = 0;
            this.ClearFields();
        }

        private void ClearFields()
        {
            this.userName.Text = string.Empty;
            this.userPhone.Text = string.Empty;
            this.userEmail.Text = string.Empty;
            this.userPassword.Text = string.Empty;
            this.userFacebook.Text = string.Empty;
            this.userAdmin.Checked = false;
            this.userTattooArtist.Checked = false;
        }


        public void SaveUserClick(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(userName.Text))
                throw new ArgumentNullException("userName", "É obrigatório informar o nome do usuário.");

            if (string.IsNullOrWhiteSpace(userEmail.Text))
                throw new ArgumentNullException("userEmail", "É obrigatório informar o email do usuário.");

            if (string.IsNullOrWhiteSpace(userPassword.Text))
                throw new ArgumentNullException("userPassword", "É obrigatório informar a senha do usuário.");

            LuckyLoot.Domain.Entities.People.User user;
            if (HasSelectedRecord)
                user = this.UserService.UpdateUser(UserID, userName.Text, userPhone.Text, userEmail.Text, userPassword.Text, userFacebook.Text, userAdmin.Checked, userTattooArtist.Checked);
            else
                user = this.UserService.CreateUser(userName.Text, userPhone.Text, userEmail.Text, userPassword.Text, userFacebook.Text, userAdmin.Checked, userTattooArtist.Checked);

            this.SelectRecord(user);
            this.SetCommandsVisibility();
            MasterPage.ShowSuccessMessage("Usuário salvo com sucesso!");
            this.BindGrid();
        }

        private void BindGrid()
        {
            var users = this.UserService.GetUsers();

            if (users.Count() > 0)
            {
                this.usersGrid.DataSource = users;
                this.usersGrid.DataBind();
                this.usersGrid.Visible = true;
                this.usersLabel.Visible = true;
            }
        }
    }
}